/*** 
 * @Author: wq
 * @Date: 2021-07-20 22:07:07
 * @LastEditTime: 2021-07-21 00:41:27
 * @LastEditors: wq
 * @Description: 
 * @FilePath: /opencv_camera/code/WinInfo/src/windowInfo.cpp
 * @CSDN： https://blog.csdn.net/u011218356 
 * @Git:  https://github.com/WQuit 
 * @Email:  779508400@qq.com  
 * @    星河灿烂，你是人间烟火
 */

#include "windowInfo.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>

WindowInfo::WindowInfo(/* args */)
{
    
}

WindowInfo::~WindowInfo()
{
}

WindowInfo* WindowInfo::instance()
{
    static WindowInfo info;
    return &info;
}

void WindowInfo::showWindowInfo()
{
    windowList();
}

std::list<windowAttributeInfo> WindowInfo::getWindowInfo()
{
    return _windowList;
}

void WindowInfo::subWindowList(Display* display, Window id)
{
    Window rootReturn = 0;
    Window parentReturn = 0;
    Window* childList = nullptr;
    uint childNum = 0;
    XQueryTree(display, id, &rootReturn, &parentReturn, &childList, &childNum);
    for(uint i = 0; i < childNum; i++)
    {
        auto it = childList[i];
        char* windowName = nullptr;
        XFetchName(display, it, &windowName);
        if(windowName == nullptr)
            continue;
        if(!std::string(windowName).empty())
        {
            XWindowAttributes xAttribute={0};
            if(XGetWindowAttributes(display, it, &xAttribute))
            {
                _windowList.push_back({std::string(windowName), it, parentReturn, xAttribute.x, xAttribute.y, xAttribute.width, xAttribute.height});
                std::cout << "WindowName:" << std::string(windowName) << " WindowID:" << it << " ParentWindowID:" << parentReturn \
                << " x:" << xAttribute.x << " y:" << xAttribute.y << " width:" << xAttribute.width << " height:" << xAttribute.height << std::endl;
            }
        }
        subWindowList(display, it);
    }
    XFree(childList);
}

void WindowInfo::windowList()
{
    auto display = XOpenDisplay(nullptr);
    auto rootWindow = DefaultRootWindow(display);
    subWindowList(display, rootWindow);
    XCloseDisplay(display);
}

 